package com.michale.system.service.impl;

import com.michale.common.character.ClassConvert;
import com.michale.common.constants.RedisCacheConstant;
import com.michale.common.domain.operate.CacheEntity;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.redis.RedisUtils;
import com.michale.system.service.CacheService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author Michale
 * @apiNote 缓存管理 业务层
 */
@Service("cacheService")
public class CacheServiceImpl implements CacheService {

    @Resource
    private RedisUtils redisUtils;

    /**
     * 查询缓存名称列表
     *
     * @return 缓存名称列表
     */
    @Override
    public List<CacheEntity> getCacheNameList() {
        final List<CacheEntity> cacheList = new ArrayList<>();
        cacheList.add(new CacheEntity(RedisCacheConstant.LOGIN_TOKEN_KEY, "用户信息"));
        cacheList.add(new CacheEntity(RedisCacheConstant.SYS_CONFIG_KEY, "配置信息"));
        cacheList.add(new CacheEntity(RedisCacheConstant.SYS_DICT_KEY, "数据字典"));
        cacheList.add(new CacheEntity(RedisCacheConstant.CAPTCHA_CODE_KEY, "验证码"));
        cacheList.add(new CacheEntity(RedisCacheConstant.REPEAT_SUBMIT_KEY, "防重提交"));
        cacheList.add(new CacheEntity(RedisCacheConstant.RATE_LIMIT_KEY, "限流处理"));
        cacheList.add(new CacheEntity(RedisCacheConstant.PWD_ERR_CNT_KEY, "密码错误次数"));
        return cacheList;
    }

    /**
     * 查询缓存键名列表
     *
     * @param cacheName 缓存名称
     * @return 缓存键名列表
     */
    @Override
    public Set<String> getCacheKeyList(String cacheName) {
        return (Set<String>) redisUtils.keys(cacheName + "*");
    }

    /**
     * 查询缓存内容
     *
     * @param cacheName 缓存名称
     * @param cacheKey  缓存键值
     * @return 缓存内容
     */
    @Override
    public CacheEntity getCacheValue(String cacheName, String cacheKey) {
        String cacheValue = ClassConvert.toString(redisUtils.getCacheObject(cacheKey));
        return new CacheEntity(cacheName, cacheKey, cacheValue);
    }

    /**
     * 清理指定名称缓存
     *
     * @param cacheName 缓存名称
     */
    @Override
    public void clearCacheName(String cacheName) {
        if (StringUtils.equals("login_tokens:", cacheName)) {
            redisUtils.deleteObject(redisUtils.keys(RedisCacheConstant.LOGIN_KEY + "*"));
        }
        redisUtils.deleteObject(redisUtils.keys(cacheName + "*"));
    }

    /**
     * 清理指定键名缓存
     *
     * @param cacheKey 缓存键名
     */
    @Override
    public void clearCacheKey(String cacheKey) {
        redisUtils.deleteObject(cacheKey);
    }

    /**
     * 根据缓存名称清理全部缓存键名
     *
     * @param cacheName 缓存名称
     */
    @Override
    public void clearCacheKeyAll(String cacheName) {
        Collection<String> keys = redisUtils.keys(cacheName + "*");
        redisUtils.deleteObject(keys);
    }
}
